package com.fc.app.service.impl;

import com.fc.app.dao.AppCategoryDao;
import com.fc.app.entity.AppCategory;
import com.fc.app.vo.AppCategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AppCategoryService {

    @Autowired
    AppCategoryDao appCategoryDao;

    public AppCategoryVo tree() {

        List<AppCategoryVo> voList = new ArrayList<>();

        List<AppCategory> list = appCategoryDao.queryAllBy(new AppCategory());

        for (AppCategory appCategory : list) {
            AppCategoryVo vo = new AppCategoryVo();

            BeanUtils.copyProperties(appCategory,vo);

            voList.add(vo);
        }

        AppCategoryVo tree = new AppCategoryVo();
        for (AppCategoryVo vo : voList) {
            if (vo.getParentid() == null){
                tree = findChildren(vo,voList);
            }

        }
        return tree;
    }

    private AppCategoryVo findChildren(AppCategoryVo vo,List<AppCategoryVo> voList){
        vo.setChildren(new ArrayList<>());

        for (AppCategoryVo categoryVo : voList) {
            if (vo.getId() == categoryVo.getParentid()){

                vo.getChildren().add(categoryVo);

                findChildren(categoryVo , voList);
            }
        }
        return vo;
    }

}
